package org.shijiagen.cart.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.apache.http.util.Asserts;
import org.shijiagen.cart.mapper.CartMapper;
import org.shijiagen.cart.service.CartService;
import org.shijiagen.clients.ProductClient;
import org.shijiagen.param.CartSaveParam;
import org.shijiagen.param.ProductCollectParam;
import org.shijiagen.param.ProductIdParam;
import org.shijiagen.pojo.Cart;
import org.shijiagen.pojo.Product;
import org.shijiagen.utils.R;
import org.shijiagen.vo.CartVo;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class CartServiceImpl implements CartService {

    private final CartMapper cartMapper;

    private final ProductClient productClient;


    @Override
    public List<CartVo> list(Integer userId) {
        List<Cart> carts = cartMapper.selectList(new QueryWrapper<Cart>().eq("user_id", userId));
        if (carts.isEmpty()) {
            return new ArrayList<>();
        }
        List<Integer> productIds = carts.stream().map(Cart::getProductId).toList();
        ProductCollectParam productCollectParam = new ProductCollectParam();
        productCollectParam.setProductIds(productIds);
        Map<Integer, Product> productMap = productClient.cartProductByIds(productCollectParam)
                .stream().collect(Collectors.toMap(Product::getProductId, product -> product));
        List<CartVo> result = new ArrayList<>();
        carts.forEach(cart -> {
            result.add(new CartVo(productMap.get(cart.getProductId()),cart));
        });
        return result;
    }

    @Override
    public CartVo save(CartSaveParam cartSaveParam) {
        // 根据商品id查询对应商品详情
        ProductIdParam productIdParam = new ProductIdParam();
        productIdParam.setProductID(cartSaveParam.getProductId());
        Product product = productClient.cartProductDetail(productIdParam);
        // 如果根据id找不到商品，则代表商品已删除直接抛异常
        Asserts.check(product != null,"该商品对象已经删除");
        // 如果商品存在但是库存为零，则代表商品没有货了直接抛异常
        Asserts.check(product.getProductNum() != 0,"该商品没有库存辣");
        // 检查该商品是否已经添加进购物车
        Cart cart = cartMapper.selectOne(new QueryWrapper<Cart>().eq("user_id", cartSaveParam.getUserId())
                .eq("product_id", cartSaveParam.getProductId()));
        // 如果商品已经在购物车里了则数量加一
        if(cart != null){
            cart.setNum(cart.getNum()+1);
            cartMapper.updateById(cart);
            return null;
        }
        // 如果商品不存在在购物车中则新增购物车商品
        Cart newCart = new Cart();
        newCart.setUserId(cartSaveParam.getUserId());
        newCart.setProductId(cartSaveParam.getProductId());
        newCart.setNum(1);
        cartMapper.insert(newCart);
        return new CartVo(product,newCart);
    }

    @Override
    public Boolean update(Cart cart) {
        ProductIdParam productIdParam = new ProductIdParam();
        productIdParam.setProductID(cart.getProductId());
        Product product = productClient.cartProductDetail(productIdParam);
        Asserts.check(cart.getNum() <= product.getProductNum(),"商品库存不足");
        Cart newCart = cartMapper.selectOne(new QueryWrapper<Cart>().eq("user_id", cart.getUserId())
                .eq("product_id", cart.getProductId()));
        newCart.setNum(cart.getNum());
        return cartMapper.updateById(newCart) > 0;
    }

    @Override
    public Boolean remove(Cart cart) {
        return cartMapper.delete(new QueryWrapper<Cart>().eq("user_id",cart.getUserId())
                .eq("product_id",cart.getProductId())) > 0;
    }

    @Override
    public void clearIds(List<Integer> cartIds) {
        cartMapper.deleteBatchIds(cartIds);
    }

    @Override
    public R check(Integer productId) {
        Long count = cartMapper.selectCount(new QueryWrapper<Cart>().eq("product_id", productId));
        return count > 0 ? R.fail("有"+count+"个购物车引用该商品") : R.ok("删除成功！");
    }
}
